var modElement = function (view, node) {
    Ext.Ajax.request({
        url: 'structure/getElement',
        params: {
            node: node.get('id')
        },
        success: function (response) {
            var element = Ext.decode(response.responseText);
            var windowHeader;
            var parentElementLabel;
            var renderedItems;

            if (element.type == 'employee') {
                var employeeId = element.id;
                var employeeLname = element.lname;
                var employeeFname = element.fname;
                var employeePname = element.pname;
                var employeeEmail = element.email;
                var employeeBirthDate = element.birthDate;
                var employeeJobPosition = element.jobPosition;
                var employeeProject = element.project;
                windowHeader = 'Сотрудник: ' + employeeLname + ' '
                    + employeeFname + ' ' + employeePname;
            } else {
                var nodeName = element.name;
                var nodeDescription = element.description;
                if (element.type == 'root')
                    windowHeader = 'Компания: ' + nodeName;
                else if (element.type == 'division')
                    windowHeader = 'Подразделение: ' + nodeName;
                else if (element.type == 'project')
                    windowHeader = 'Проект: ' + nodeName;
            }

            if (element.type == 'employee') {

                var id = Ext.create('Ext.form.TextField', {
                    xtype: 'textfield',
                    id: 'id',
                    fieldLabel: 'ID',
                    value: employeeId,
                    anchor: '100%',
                    readOnly: true
                });

                var lname = Ext.create('Ext.form.TextField', {
                    xtype: 'textfield',
                    id: 'lname',
                    fieldLabel: 'Фамилия',
                    value: employeeLname,
                    anchor: '100%'
                });

                var fname = Ext.create('Ext.form.TextField', {
                    xtype: 'textfield',
                    id: 'fname',
                    fieldLabel: 'Имя',
                    value: employeeFname,
                    anchor: '100%'
                });

                var pname = Ext.create('Ext.form.TextField', {
                    xtype: 'textfield',
                    id: 'pname',
                    fieldLabel: 'Отчество',
                    value: employeePname,
                    anchor: '100%'
                });

                var email = Ext.create('Ext.form.TextField', {
                    xtype: 'textfield',
                    id: 'email',
                    fieldLabel: 'Эл. почта',
                    value: employeeEmail,
                    vtype: 'email',
                    anchor: '100%'
                });

                var birthDate = Ext.create('Ext.form.DateField', {
                    xtype: 'Datefield',
                    id: 'birthDate',
                    fieldLabel: 'Дата рождения',
                    format: 'd.m.Y',
                    value: new Date(employeeBirthDate),
                    anchor: '100%'
                });

                var jobPositionStore = Ext.create('Ext.data.Store', {
                    fields: ['data'],
                    proxy: {
                        type: 'ajax',
                        url: 'employee/getJobPositions',
                        autoLoad: true
                    }
                });

                var jobPosition = Ext.create('Ext.form.ComboBox', {
                    xtype: 'combo',
                    id: 'jobPosition',
                    fieldLabel: 'Должность',
                    displayField: 'data',
                    valueField: 'data',
                    value: employeeJobPosition,
                    allowBlank: false,
                    editable: false,
                    typeAhead: true,
                    selectOnFocus: true,
                    triggerAction: 'all',
                    anchor: '100%',
                    store: jobPositionStore
                });

                var projectStore = Ext.create('Ext.data.Store', {
                    fields: ['id', 'data'],
                    proxy: {
                        type: 'ajax',
                        url: 'project/getAllProjects',
                        autoLoad: true
                    }
                });

                var project = Ext.create('Ext.form.ComboBox', {
                    xtype: 'combo',
                    id: 'project',
                    fieldLabel: 'Проект',
                    displayField: 'data',
                    valueField: 'id',
                    value: employeeProject,
                    allowBlank: false,
                    editable: false,
                    typeAhead: true,
                    selectOnFocus: true,
                    triggerAction: 'all',
                    anchor: '100%',
                    store: projectStore
                });

            } else {

                var name = Ext.create('Ext.form.TextField', {
                    xtype: 'textfield',
                    id: 'name',
                    fieldLabel: 'Название',
                    value: nodeName,
                    anchor: '100%'
                });

                var description = Ext.create('Ext.form.TextArea', {
                    xtype: 'textarea',
                    id: 'description',
                    fieldLabel: 'Описание',
                    value: nodeDescription,
                    allowBlank: true,
                    anchor: '100%'
                });
            }

            if (node.get('id').match(/Emp_\d*/)) {
                renderedItems = [lname, fname, pname, birthDate, email, jobPosition, project];
            } else {
                renderedItems = [name, description];
                if (node.get('id').match(/Proj_\d*/)) {
                    parentElementLabel = 'Подразделение';
                } else if (node.get('id').match(/Div_\d*/)) {
                    parentElementLabel = 'Компания';
                }

                var parentElement = Ext.create('Ext.form.TextField', {
                    xtype: 'textfield',
                    id: 'parentElement',
                    fieldLabel: parentElementLabel,
                    value: node.parentNode.get('text'),
                    anchor: '100%',
                    readOnly: true
                });

                renderedItems.push(parentElement);
            }

            var modActionForm = Ext.create('Ext.form.FormPanel', {
                baseCls: 'x-plain',
                defaultType: 'textfield',
                items: renderedItems
            });

            var modActionWindow = Ext.create('Ext.Window', {
                title: windowHeader,
                width: 500,
                resizable: false,
                plain: true,
                bodyStyle: 'padding: 5px 5px 0 5px; border: none;',
                buttonAlign: 'right',
                items: modActionForm,
                layout: 'fit',
                buttons: [
                    {
                        text: 'Изменить',
                        handler: function () {
                            if (modActionForm.getForm().isValid()) {
                                modActionForm.getForm().submit({
                                    url: 'structure/modElement',
                                    params: {
                                        node: node.get('id')
                                    },
                                    waitMsg: 'Пожалуйста, ожидайте',
                                    success: function (form, action) {
                                        var tree = Ext.getCmp('tree');
                                        modActionWindow.close();

                                        if (node.get('id').match(/Emp_\d*/)) {
                                        	var oldNodeAncestorId = tree.getStore().getNodeById(node.get('id')).parentNode.get('id')
                                            tree.getStore().reload({node: tree.getStore().getNodeById(node.get('id')).parentNode,
                                                callback: function () {
                                                	tree.getStore().reload({node: tree.getStore().getNodeById(action.result.divisionAncestor),
                                                        callback: function () {
		                                                    tree.getStore().reload({node: tree.getStore().getNodeById(action.result.projectAncestor),
		                                                        callback: function () {
		                                                        	tree.expandPath(tree.getStore().getNodeById(oldNodeAncestorId).getPath());
		                                                            tree.expandPath(tree.getStore().getNodeById(action.result.projectAncestor).getPath());
		                                                            tree.selectPath(tree.getStore().getNodeById(action.result.modEmployee).getPath());
		                                                            nodeData(this, tree.getStore().getNodeById(action.result.modEmployee));
		                                                            Ext.getCmp('infoPanel').doLayout();
		                                                        }
		                                                    });
                                                        }
                                                	});
                                                }
                                            });
                                        } else {
                                            var nodeExpanded = node.isExpanded();
                                            tree.getStore().read({node: tree.getStore().getNodeById(node.get('id')).parentNode,
                                                callback: function () {
                                                    tree.selectPath(tree.getStore().getNodeById(node.get('id')).getPath());
                                                    if (nodeExpanded) {
                                                        tree.expandPath(tree.getStore().getNodeById(node.get('id')).getPath());
                                                    }
                                                    nodeData(this, node);
                                                    Ext.getCmp('infoPanel').doLayout();
                                                }
                                            });
                                        }
                                        Ext.Msg.alert('ОТЧЕТ', action.result.message);
                                    },
                                    failure: function (form, action) {
                                        if (action.failureType === Ext.form.action.Action.CONNECT_FAILURE) {
                                            Ext.Msg.alert('ОШИБКА', 'Ошибка соединения с сервером');
                                        } else if (action.failureType === Ext.form.action.Action.SERVER_INVALID) {
                                            Ext.Msg.alert('ОШИБКА', action.result.message);
                                        }
                                    }
                                });
                            }
                        }
                    },
                    {
                        text: 'Отмена',
                        handler: function () {
                            modActionForm.getForm().reset();
                            modActionWindow.close();
                        }
                    }
                ]
            });

            modActionWindow.show();
        },
        failure: function (response) {
            Ext.Msg.alert('Ошибка подключения к серверу');
        }
    });
};